package com.bysc.commentservice.config;

import com.github.houbb.sensitive.word.api.IWordDeny;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MyWordDeny implements IWordDeny {
    @Override
    public List<String> deny() {
        List<String> denyWords = new ArrayList<>();
        try {
            ClassPathResource classPathResource = new ClassPathResource("/myDenyWords.txt");
            InputStream inputStream = classPathResource.getInputStream();
// 调用 readFileToList 方法读取文件内容并添加到 List 中
            denyWords = readFileToList(inputStream);

            /*ClassPathResource resource = new ClassPathResource("/myDenyWords.txt");
            URL resource = this.getClass().getResource("/myDenyWords.txt");
            Path myAllowWordsPath = Paths.get(resource.toURI());
            denyWords = Files.readAllLines(myAllowWordsPath, StandardCharsets.UTF_8);*/
        } catch (IOException ioException) {
            log.error("读取敏感词文件错误：{}", ioException);
        }
        return denyWords;
    }

    public static List<String> readFileToList(InputStream inputStream) {
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }
}